﻿using System;
using Gonte.Collections;

namespace Gonte.Validation
{
    public class FieldRangeValidator
        : FieldValidator
    {
        private const string ValueOutOfRangeError = "Value: {0} is out of range [{1}, {2}]";
        private const string NotIComparable = "Type: {0} does not implement IComparable";

        public FieldRangeValidator(Object minValue, Object maxValue)
        {
            minValue_ = minValue;
            maxValue_ = maxValue;
        }

        public override bool Validate(Object value)
        {
            if (value == null)
            {
                return true;
            }

            if (value is DateTime)
            {
                if (!Range<DateTime>.IsInRange((DateTime)value, DateTime.Parse(minValue_.ToString()), DateTime.Parse(maxValue_.ToString())))
                {
                    error_ = string.Format(ValueOutOfRangeError, value, minValue_, maxValue_);
                    return false;
                }
            }
            else if (value is IComparable)
            {
                if (!Range<IComparable>.IsInRange((IComparable)value, (IComparable)minValue_, (IComparable)maxValue_))
                {
                    error_ = string.Format(ValueOutOfRangeError, value, minValue_, maxValue_);
                    return false;
                }
            }
            else // Not handled data field
            {
                error_ = string.Format(NotIComparable, value.GetType());
                return false;
            }

            return true;
        }

        private Object minValue_;
        private Object maxValue_;
    }
}
